package com.nhjf.dao.system;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Repository;

import com.nhjf.dao.BaseDao;
import com.nhjf.model.system.Resource;
import com.nhjf.pojo.qo.system.ResourceQo;


@Repository
public class ResourceDao extends BaseDao<Resource,ResourceQo>{

	@Override
	protected Criteria buildCriteria(Criteria criteria, ResourceQo qo) {
		if(qo != null){
			if(qo.getUserId()!=null) {
//				criteria.setFetchMode("roleSet.id", FetchMode.JOIN);
//				criteria.setFetchMode("roleSet.userList.id", FetchMode.JOIN);
//				criteria.add(Restrictions.eq("id",qo.getUserId() ));
				criteria.createCriteria("roleSet", JoinType.LEFT_OUTER_JOIN).createCriteria("userList", JoinType.LEFT_OUTER_JOIN).add(Restrictions.eq("id", qo.getUserId()));
			}
			if(qo.getRoleId()!=null) {
				criteria.createCriteria("roleSet", JoinType.LEFT_OUTER_JOIN).add(Restrictions.eq("id",qo.getRoleId()));
			}
			if(qo.getType() != null){
				criteria.add(Restrictions.eq("type", qo.getType()));
			}
			
			if(qo.getParentId() != null){
				if(qo.getQueryParent()){
					criteria.add(Restrictions.or(Restrictions.eq("parentId", qo.getParentId()),
							Restrictions.eq("id",qo.getParentId())));
				}else{
					criteria.add(Restrictions.eq("parentId", qo.getParentId()));
				}
				
			}
			
			if(qo.getResourceId() != null){
				criteria.add(Restrictions.eq("id", qo.getResourceId()));
			}
			
			if(StringUtils.isNotBlank(qo.getUrl())){
				criteria.add(Restrictions.like("url", qo.getUrl(),MatchMode.ANYWHERE));
			}
			
			if(StringUtils.isNotBlank(qo.getNumber())){
				criteria.add(Restrictions.like("number", qo.getNumber()));
			}
			criteria.addOrder(Order.asc("id"));
			criteria.addOrder(Order.asc("number"));
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		}
		return criteria;
	}

	@Override
	protected Class<Resource> getEntityClass() {
		return Resource.class;
	}

}
